package com.example.myapplication.observetheglobalstate;

import android.app.usage.NetworkStats;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.example.myapplication.viewmodelsharedcommondata.vd2.CustomProjectLiveData;

/**
 * 此观察者  去  观察BaseActivity 的生命周期
 * 有一双眼睛  盯着 所有  Activity  的生命周期
 */
public class CustomNetworkStateManager implements DefaultLifecycleObserver {


    private static final CustomNetworkStateManager S_MANAGER = new CustomNetworkStateManager();

    //  如果网络发生改变的时候让  BaseFragment  --   TODO  子类可以重写该方法,统一的网络状态通知和处理
//    public final CustomProjectLiveData<NetworkStats> mNetworkStateCallback = new CustomProjectLiveData<>();CustomProjectLiveData


    private NetworkReceive mNetworkReceive;

    private CustomNetworkStateManager() {

    }

    public static CustomNetworkStateManager getInstance() {
        return S_MANAGER;
    }

    /**
     * 那么观察到  BasetActivity  的生命周期方法后
     * 注册一个广播，此广播只可以接受到的信息  然后输出  网络不给力
     * @param owner the component, whose state was changed
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onResume(owner);
        mNetworkReceive = new NetworkReceive();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        if (owner instanceof AppCompatActivity){
            ((AppCompatActivity) owner).registerReceiver(mNetworkReceive,filter);
        } else if (owner instanceof Fragment) {
            ((Fragment) owner).getActivity().registerReceiver(mNetworkReceive,filter);
        }
    }


    /**
     * 那么观察到  BaseActivity  的生命周期方法后做什么事情呢 ？
     *    就是移除一个广播
     * @param owner the component, whose state was changed
     */
    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onPause(owner);
        if (owner instanceof AppCompatActivity) {
            ((AppCompatActivity) owner).unregisterReceiver(mNetworkReceive);
        } else if (owner instanceof Fragment) {
            ((Fragment) owner).getActivity().unregisterReceiver(mNetworkReceive);
        }

    }
}
